using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using B.MESUI.Login.BasicData_UI.BasicData.Select;
using Newtonsoft.Json.Linq;

namespace B.MESUI.Login.BasicData_UI.Customer
{
    public class CustomerService
    {
        public async Task<(List<CustomerDTO> list, int total)> GetCustomers(int pageIndex, int pageSize, string code, string name)
        {
            string url = $"http://localhost:5198/api/Customer/GetPageCustomer?PageIndex={pageIndex}&PageSize={pageSize}";
            if (!string.IsNullOrEmpty(code)) url += $"&CUSTOMER_CODE={code}";
            if (!string.IsNullOrEmpty(name)) url += $"&CUSTOMER_NAME={name}";
            using (HttpClient client = new HttpClient())
            {
                var resp = await client.GetAsync(url);
                string json = await resp.Content.ReadAsStringAsync();
                var jobj = JObject.Parse(json);
                int totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                var pageList = jobj["pageDatas"] as JArray;
                var dataList = new List<CustomerDTO>();
                if (pageList != null)
                {
                    foreach (var item in pageList)
                    {
                        dataList.Add(item.ToObject<CustomerDTO>());
                    }
                }
                return (dataList, totalCount);
            }
        }

        public async Task DeleteCustomer(string customerCode)
        {
            string url = $"http://localhost:5198/api/Customer/Delete?customerCode={customerCode}";
            using (HttpClient client = new HttpClient())
            {
                await client.DeleteAsync(url);
            }
        }
    }
} 